<template>
  <PageLayout full :page-style="pageStyle">
    <template #header>
      <HeaderLayout show-back>
        <view>{{ $t('Pairing.ChooseMode.Navigator.ScanQRCode.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="container">
      <view class="content">
        <view class="autoSelect">
          <view class="cameraView">
            <camera
              v-if="showCamera"
              device-position="back"
              mode="scanCode"
              flash="off"
              resolution="high"
              frame-size="large"
              style="width: 100%; height: 100%"
              @scancode="scanCode"
            ></camera>
          </view>
          <view class="noFound">
            <view class="title">{{ $t('Pairing.ChooseMode.ScanQRCode.Tips.Text') }}</view>
            <image class="noFoundContent" :src="ImageUrl" mode="widthFix" />
            <view class="subTitle" hover-class="is-hovering" @click="toScanError"
              >{{ $t('Pairing.ChooseMode.NOFoundQRCode.Button.Text') }}></view
            >
          </view>
        </view>
      </view>
    </view>
    <Modal
      :visible="isCameraAuthSettingOpen"
      :title="$t('Pairing.ChooseMode.OpenCameraAuthorize.Dialog.Tilte')"
      @ok="goToSettings"
      :ok-text="$t('APP.Common.ISee.Text')"
    >
      <view style="text-align: left">{{ $t('Pairing.ChooseMode.CameraAuthorize.Dialog.Text') }}</view>
      <image :src="cameraAuthUrl" style="width: 100%" mode="aspectFit"></image>
    </Modal>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import Modal from '@/common/modal.vue'
import '@/pages/pairing/pairingHelper.js'
import netconfig from '@/config/netconfig'
import { useAuthStore } from '@/store/auth'
import { useGlobalStore } from '@/store/global'
import { onHide, onLoad, onShow } from '@dcloudio/uni-app'
import { reportEventData } from '@/dataReport/dataReportUtil'
import keyUtils from '@/dataReport/keyUtils'
import { getParam, isEnergTag } from '../uitls/utils'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import $$Rangers from '@datarangers/sdk-mp'

const pageStyle = {
  backgroundColor: '#fff',
}
let authStore = useAuthStore()
let global = useGlobalStore()
const plugin = requirePlugin('pairing-plugin')

let isPageShow = ref()
const isCameraAuthSettingOpen = ref(false)
const showCamera = ref(true)
let cameraAuthUrl: string
let scaned: boolean | number = 0
let choosenVib: string = ''
let pairingSource: string
let hotSpotpwd: string
let nav: boolean = false
let ImageUrl: string

ImageUrl = netconfig.ASSETSPRE + '/Assets/icons/img_scanQRcode_tips.png'
cameraAuthUrl = netconfig.ASSETSPRE + '/Assets/icons/img_pairing_CameraOff.png'
onLoad(() => {
  plugin.initPluginHttpEnvironment(netconfig.PLUGIN_ENV, netconfig.isTester)
  plugin.initPluginData(authStore.accessToken, authStore.accessOpenId, authStore.key, authStore.iv)
})
onShow(() => {
  uni.getSetting({
    success: (res) => {
      console.log('getSetting', 'success', res, res.authSetting['scope.camera'])
      if (res.authSetting['scope.camera'] === false) {
        isCameraAuthSettingOpen.value = true
      } else {
        if (!showCamera.value) {
          showCamera.value = true
        }
      }
    },
    fail(error) {
      console.log('getSetting', 'fail', error)
    },
  })
})
onHide(() => {})
function toScanError() {
  safeTrack(() => {
    trackEvent(
      'click_cannot_find_qr_code',
      {},
      TrackType.BusinesssScene,
      'Pairing.ChooseMode.NOFoundQRCode.Button.Text'
    )
  })
  uni.navigateTo({
    url: '/pages/pairing/scanError/scanError?noScan=true',
  })
}
function binderror(e: any) {
  console.log(e)
}
/**
 * 扫码成功回调
 * @param {*} e
 */
function scanCode(e: any) {
  console.log('scanCode', e)
  if (!isPageShow) {
    return
  }
  if (!scaned) {
    scaned = !0
    checkQRcode(e.detail.result).then(
      (res) => {
        console.error('scanCode....suc', res)
        pairingSource = '扫描二维码'
        wx.showLoading({
          title: '跳转中...',
        })
        reportEventData(keyUtils.KEY_SCANQRCODE, {
          scan_type: '调用相机',
          is_success: true,
          product_vib: choosenVib,
        })
        uni.navigateTo({
          url:
            '/pages/pairing/confirmAppliance/index?vib=' +
            choosenVib +
            '&pairingSource=' +
            pairingSource +
            '&hotSpotpwd=' +
            hotSpotpwd,
          complete: () => {
            setTimeout(() => {
              scaned = 0
            }, 1500)
          },
        })
      },
      (error) => {
        console.log('scanCode....error', error)
        reportEventData(keyUtils.KEY_SCANQRCODE, {
          scan_type: '调用相机',
          is_success: false,
          product_vib: choosenVib,
          error_message: '扫码失败',
          error_code: error.code,
        })
        wx.navigateTo({
          url: `/pages/pairing/scanErroreTip/scanErroreTip?result=${global.scanErrorKeys[error.code]}&errorCode=${
            error.code
          }`,
          complete: (res) => {
            setTimeout(() => {
              nav = false
              scaned = 0
            }, 1500)
          },
        })
      }
    )
  }
}

// 解析扫码出来的scene参数等
const getURLParameters = (url: any) => {
  let matchUrl = url.match(/([^?=&]+)(=([^&]*))/g)
  if (matchUrl && matchUrl.length > 0) {
    return matchUrl.reduce((a: any, v: any) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {})
  } else {
    return null
  }
}

function checkQRcode(res: any) {
  console.log('res', res)
  let vib = getParam(res, 'EN')
  hotSpotpwd = getParam(res, 'pd')
  if (vib == '') {
    vib = getParam(res, 'vib')
  }

  // 配置utm_source
  safeTrack(() => {
    let scene = getURLParameters(res)
    if (scene) {
      console.log('scene', scene)
      $$Rangers.config({
        utm_source: scene.scene ? scene.scene : 'hc',
      })
    }
  })

  console.log('checkQRcode', 'vib', vib, hotSpotpwd)

  return new Promise(async function (resolve, reject) {
    if (vib == '') {
      // 扫描的是能效标签
      if (isEnergTag(res)) {
        reject({
          code: 2,
        })
      } else {
        // 扫描的不是能效标签，是其他无关的二维码
        reject({
          code: 3,
        })
      }
      return
    }
    choosenVib = vib
    nav = false
    resolve(res)
  })
}
function goToSettings() {
  uni.openSetting({
    success(res) {
      console.log(res.authSetting)
    },
  })
  isCameraAuthSettingOpen.value = false
}
function cancelCameraAuthSettingOpen() {
  isCameraAuthSettingOpen.value = false
}
</script>

<style lang="less">
.container {
  position: relative;
  width: 100%;
  height: 100%;
}

.content {
  width: 100%;
  /* height: calc(100% - 272rpx); */
  height: 100%;
  overflow: hidden;
  position: relative;
}

.autoSelect {
  width: 100%;
  height: 100%;
  position: relative;
}

.autoSelect .cameraView {
  width: 100%;
  height: 73%;
  position: relative;
}

.autoSelect .noFound {
  width: 100%;
  height: 27%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: #fff;
  box-sizing: border-box;
}

.autoSelect .noFound .title {
  text-align: center;
  color: var(--dark-color);
  font-size: 36rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.autoSelect .noFound .subTitle {
  text-align: center;
  font-size: 28rpx;
  color: var(--primary-color);
  font-size: 32rpx;
  font-weight: 600;
  letter-spacing: 1.12rpx;
  text-decoration-line: underline;
  margin-top: 26rpx;
  &.is-hovering {
    filter: brightness(0.8);
  }
}

.autoSelect .noFound .noFoundContent {
  width: 630rpx;
  margin: 0 auto;
}
</style>
